import * as services from 'services/inquiry';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'inquiry',
  // 问诊单相对应的接口 

  state: {
    list: [],
    detail: {},
    tonguePic:"",
    facePic:"",
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
      let hospitalId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).hospitalId;
      const Inquiries = yield call(services.queryInquiryList, patientId, hospitalId);
      yield put({ type: 'save', payload: { list: Inquiries.data || [] } });
    },

    * query({ payload: {id } }, { call, put }) {
      let patientId = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid"))).patientId;
      const data = yield call(services.queryInquiryDetail, id, patientId);
      yield put({ type: 'save', payload: { detail: data.data  } });
    },

    * submit({ payload: data }, { call, put }) {
      const res = yield call(services.saveInquiry, data);
      yield put(routerRedux.goBack());
    },

    * saveImage({ payload: { field, image } }, { call, put }) {
      const images = yield put({ type: 'save', payload: { [field]: image } });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query, ...rest }) => {
        // TODO: APP嵌入H5的授权临时解决方案
        if (/inquiry$/.test(pathname)) {
          dispatch({ type: 'fetch'});
        }

        if (/inquiry\/\d+/.test(pathname)) {
          dispatch({ type: 'query', payload: {id:rest.state.id } });
        }

        if (/sheet$/.test(pathname)) {
          dispatch({ type: 'save', payload: { detail: {} } });
        }
      });
    },
  },
};
